package com.glsc.ngateway.opmanage.service.report.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.glsc.ngateway.common.base.domain.mysql.opmanage.report.excel.DCMNow;
import com.glsc.ngateway.common.base.repo.mysql.opmanage.report.excel.DCMNowRepo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class DCMNowListener extends AnalysisEventListener<DCMNow> {

    private static final int BATCH_COUNT = 3000;
    List<DCMNow> list=new ArrayList<DCMNow>();

    private DCMNowRepo dcmNowRepo;
    private Date date;

    public DCMNowListener(){
    }

    public DCMNowListener(DCMNowRepo dcmNowRepo, Date date){
        this.dcmNowRepo=dcmNowRepo;
        this.date=date;
    }

    @Override
    public void invoke(DCMNow data, AnalysisContext analysisContext) {
        data.setDate(date);
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }

    }

    //读取表头内容
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
    }
    //读取完成之后
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData(){
        dcmNowRepo.saveAll(list);
    }
}
